<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
      row-key="groupNo"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增</el-button>
        <el-button type="primary" plain @click="EditGroup(scope.selectedList)">编辑</el-button>
        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedList)">
          批量删除组
        </el-button>
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作
      <template #operation="scope">
        <el-button type="primary" link :icon="Avatar" @click="settingRoleAuth(scope.row)">设置权限</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template> -->
    </ProTable>
    <TreeFilter2 ref="authRef" @send-data="sendDataAddFrom" />
    <UserDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { User, RoleManager, dataDictionary } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/views/accessControl/roleManagement/components/ImportExcel/index.vue";
import UserDrawer from "@/views/dataDictionary/groupManagement/components/groupDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import TreeFilter2 from "@/views/accessControl/roleManagement/components/authSetting/openSetting.vue";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Avatar } from "@element-plus/icons-vue";
import {
  getUserList,
  deleteUser,
  editUser,
  addUser,
  changeUserStatus,
  resetUserPassWord,
  exportUserInfo,
  BatchAddUser
} from "@/api/modules/user";

import { roleFind, deleteRole, tempRole, importRoleData, exportRole, setResourceByRoleIds } from "@/api/modules/accessController";
import { dataDictionaryGroupFind, deleteGroup, exportDataDictionaryGroup } from "@/api/modules/dataDictionary";

const router = useRouter();
// const dialogTableVisible = ref(false);
// 跳转详情页
const toDetail = () => {
  router.push(`/proTable/useProTable/detail/${Math.random().toFixed(3)}?params=detail-page`);
};

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行

const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

const settingAuthRoleIds = ref("");
//子组件弹窗回调方法
const sendDataAddFrom = (data: any) => {
  console.log("回调了");
  console.log(data);
  setResourceByRoleIds(data + "-" + settingAuthRoleIds.value).then(res => {
    if (res.toString() == "true") {
      ElMessage.success("权限设置成功");
      proTable.value?.clearSelection();
      proTable.value?.getTableList();
    } else {
      ElMessage.error("权限设置失败");
      proTable.value?.clearSelection();
      proTable.value?.getTableList();
    }
  });
};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "";
  newParams.sord = "desc";
  delete newParams.pageNum;
  delete newParams.pageSize;
  return dataDictionaryGroupFind(newParams, "reDto", ["_search", "sidx", "sord", "page", "rows"]);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};

// 表格配置项
const columns = reactive<ColumnProps<dataDictionary.ResDataDictionaryList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "groupNo", label: "Id", sortable: true },
  { prop: "groupName", label: "名称", search: { el: "input" }, sortable: true },
  { prop: "groupCode", label: "编码", search: { el: "input" }, sortable: true }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// 删除用户信息
const deleteAccount = async (params: dataDictionary.ResDataDictionaryList) => {
  batchDelete([params]);
  //await useHandleData(deleteUser, { id: [params.id] }, `删除【${params.username}】用户`);
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 批量删除用户信息
const batchDelete = async (id: any[]) => {
  console.log(id);
  let NameStr = "";
  let idsStr = "";
  for (let i = 0; i < id.length; i++) {
    if (idsStr == "") {
      idsStr = "?groupNo=" + id[i].groupNo;
    } else {
      idsStr = idsStr + "&groupNo=" + id[i].groupNo;
    }
    NameStr = NameStr + id[i].groupName + ",";
  }
  ElMessageBox.confirm("是否删除选中的组：" + NameStr + " ？", "删除确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      console.log("sssssssssssaaaaaaaaaaa");
      console.log(idsStr);
      //await useHandleData(deleteUser, { id }, "删除所选用户信息");
      deleteGroup(idsStr).then(res => {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        proTable.value?.clearSelection();
        proTable.value?.getTableList();
      });
    })
    .catch(() => {
      console.log("saaaaaaaaaaaaaaaaaaw2");
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

// 重置用户密码
const resetPass = async (params: User.ResUserList) => {
  await useHandleData(resetUserPassWord, { id: params.id }, `重置【${params.username}】用户密码`);
  proTable.value?.getTableList();
};

// 切换用户状态
const changeStatus = async (row: User.ResUserList) => {
  await useHandleData(changeUserStatus, { id: row.id, status: row.status == 1 ? 0 : 1 }, `切换【${row.username}】用户状态`);
  proTable.value?.getTableList();
};

// 导出用户列表
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(exportDataDictionaryGroup, "数据字典分组列表", proTable.value?.searchParam)
  );
};

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: "角色",
    tempApi: tempRole,
    importApi: importRoleData,
    getTableList: proTable.value?.getTableList
  };
  dialogRef.value?.acceptParams(params);
};
const authRef = ref<InstanceType<typeof TreeFilter2> | null>(null);
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<dataDictionary.ResDataDictionaryList> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? addUser : title === "编辑" ? editUser : editUser, //这两个接口不用的，在确认按钮自定义了逻辑
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
  proTable.value?.clearSelection();
};

const EditGroup = async (id: any[]) => {
  if (id.length == 0) {
    ElMessage.error("至少选择一个组");
    return;
  } else if (id.length == 1) {
    let title = "编辑";
    const params = {
      title,
      isView: title === "查看",
      row: { ...id[0] },
      api: title === "新增" ? addUser : title === "编辑" ? editUser : editUser, //这两个接口不用的，在确认按钮自定义了逻辑
      getTableList: proTable.value?.getTableList
    };
    drawerRef.value?.acceptParams(params);
    proTable.value?.clearSelection();
  } else {
    ElMessage.error("只能编辑一个组");
    return;
  }
};
</script>
